﻿Imports System.Text
Imports Framework


Imports ProtoBuf
Imports System.Runtime.Serialization


<DataContract>
Public Class CDefaultValue : Implements IComparable(Of CDefaultValue)
	'Data
	<DataMember(Order:=1)> Public TableName As String
	<DataMember(Order:=2)> Public Name As String
	<DataMember(Order:=3)> Public Definition As String
	<DataMember(Order:=4)> Public ColumnName As String
	<DataMember(Order:=5)> Public MD5 As Guid

	'PreConstructor
	Shared Sub New()
		CProto.Prepare(Of CDefaultValue)()
	End Sub

	'Constructor
	Protected Sub New()
	End Sub
	Public Sub New(dr As DataRow)
		Me.Name = CAdoData.GetStr(dr, "DefaultConstraint")
		Me.TableName = CAdoData.GetStr(dr, "TableName")
		Me.ColumnName = CAdoData.GetStr(dr, "ColName")
		Me.Definition = CAdoData.GetStr(dr, "DefaultValue")
		Me.MD5 = CBinary.MD5_(TableName, ColumnName, Definition)
	End Sub
	Public Sub New(table As String, name As String, definition As String, colName As String)
		Me.TableName = table
		Me.Name = name
		Me.Definition = definition
		Me.ColumnName = colName
		Me.MD5 = CBinary.MD5_(TableName, ColumnName, definition)
	End Sub
	Public Overrides Function ToString() As String
		Return String.Concat(TableName, ".", ColumnName, "=", Definition, " [", Name, "]")
	End Function
	Public ReadOnly Property TableName_ As String
		Get
			Dim sb As New StringBuilder
			Dim ss As String() = TableName.Split(CStr(".").ToCharArray)
			If ss.Length = 2 Then
				Return String.Concat("[", ss(0), "].[", ss(1), "]")
			End If
			Return TableName
		End Get
	End Property
	Public ReadOnly Property DefaultName_ As String
		Get
			Return String.Concat(TableName_, ".[", Name, "]")
		End Get
	End Property

	Public Function CreateScript() As String
		Return String.Concat("ALTER TABLE ", TableName_, " ADD CONSTRAINT ", Name, " DEFAULT ", Definition, " FOR ", ColumnName)
	End Function
	Public Function DropScript() As String
		Return String.Concat("ALTER TABLE ", TableName_, " DROP CONSTRAINT [", Name, "]")
	End Function

	Public Function CompareTo(other As CDefaultValue) As Integer Implements IComparable(Of CDefaultValue).CompareTo
		Dim i As Integer = Me.TableName.CompareTo(other.TableName)
		If i <> 0 Then Return i
		i = Me.ColumnName.CompareTo(other.ColumnName)
		If i <> 0 Then Return i
		i = -Me.Definition.CompareTo(other.Definition)
		If i <> 0 Then Return i
		Return Me.Name.CompareTo(other.Name)
	End Function
End Class